package com.yunsoft.gateway.interceptor.handler;

import com.fld.central.common.model.code.BaseCode;
import com.fld.central.common.model.exception.SpiException;
import com.fld.platform.commons.entity.auth.Credentials;
import com.fld.platform.commons.entity.auth.CredentialsHolder;
import com.yunsoft.gateway.annotation.Auth;
import com.yunsoft.gateway.annotation.ExcludeAuth;
import com.yunsoft.gateway.annotation.WebInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;

/**
 * 登录认证拦截器
 * @author summerrains
 *
 */
@WebInterceptor(name = "authHandlerInterceptor", pathPatterns = { "/**" }, order = 2)
public class AuthHandlerInterceptor extends BaseHandlerInterceptor {

	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		//
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取方法上的注解
		ExcludeAuth excludeAuth = findAnnotation(handlerMethod,ExcludeAuth.class);
		if(excludeAuth != null) {
			return true;
		}
        Auth auth = findAnnotation(handlerMethod,Auth.class);
        // 如果方法上的注解为空 则获取类的注解
        // 如果标记了注解，则判断权限
        if (auth != null) {
            //
//        	checkAuthorization(request);  //gateway已经调用过该方法了，直接使用
        	Credentials credentials = CredentialsHolder.get();
        	if(credentials == null) {
        		throw new SpiException(BaseCode.JWT_NO_LOGIN,"未登录");
        	}
        }
        return true;
	}
}
